#!/usr/bin/env python
import threading
import time
import random

class PrintThread(threading.Thread):
    def __init__(self, threadName):
        threading.Thread.__init__(self, name = threadName)
        self.sleepTime = random.randint(1,3)
        print "Name: %s; sleep: %d" % (self.getName(), self.sleepTime)

    def run(self):
        lock.acquire()        #add this
        print "%s going to sleep for %s second(s)"\
              % (self.getName(), self.sleepTime)
        time.sleep(self.sleepTime)
        print self.getName(), 'done sleeping'
        lock.release()        #add this

num=10
threadList=[]
lock=threading.RLock()        #add this
for i in range(1,num+1):
    thread = PrintThread('thread'+str(i))
    threadList.append(thread)

print '\nStarting threads'

for i in threadList:
    i.start()

print 'All threads started\n'

for i in threadList:
    i.join()

print 'All threads stoped\n'
